<template>
  <div class="app-container">
    <el-row :gutter="20">
      <!-- 左侧统计面板 -->
      <el-col :span="6">
        <el-card class="box-card" v-loading="loading">
          <div class="total-stats">
            <div class="stat-item">
              <div class="title">总警力数</div>
              <div class="count">
                <span>{{ policeForceData.totalPolice }}人</span>
                <div class="sub-count">
                  <div>民警: {{ policeForceData.regularPolice }}</div>
                  <div>辅警: {{ policeForceData.auxiliaryPolice }}</div>
                </div>
              </div>
            </div>
            <div class="stat-item">
              <div class="title">在岗警力</div>
              <div class="count">
                <span>{{ policeForceData.onDutyTotal }}人</span>
                <div class="sub-count">
                  <div>在岗民警: {{ policeForceData.onDutyRegular }}</div>
                  <div>在岗辅警: {{ policeForceData.onDutyAuxiliary }}</div>
                </div>
              </div>
            </div>
          </div>

          <div class="duty-stats">
            <div class="title">当日勤务监管</div>
            <div class="duty-items">
              <div class="duty-item">
                <div>在线点位</div>
                <div>应到 {{ dutyMonitorData.onlinePoints.scheduled }}人 实到 {{ dutyMonitorData.onlinePoints.actual }}人</div>
              </div>
              <div class="duty-item">
                <div>线下巡逻</div>
                <div>应到 {{ dutyMonitorData.offlinePatrol.scheduled }}人 实到 {{ dutyMonitorData.offlinePatrol.actual }}人</div>
              </div>
            </div>
          </div>

          <div class="month-stats">
            <div class="title">本月勤务统计</div>
            <el-table :data="monthlyStats" border style="width: 100%">
              <el-table-column prop="type" label="类型" width="100"></el-table-column>
              <el-table-column prop="count" label="次数"></el-table-column>
            </el-table>
          </div>

          <!-- 轨迹信息面板 -->
          <div class="track-info" v-if="selectedPolice">
            <div class="title">轨迹信息 - {{ selectedPolice.name }}</div>
            <div class="track-stats">
              <div class="track-item">
                <span>总里程：</span>
                <span class="value">{{ trackInfo.totalDistance }}km</span>
              </div>
              <div class="track-item">
                <span>巡逻时长：</span>
                <span class="value">{{ trackInfo.patrolTime }}小时</span>
              </div>
              <div class="track-item">
                <span>停留点：</span>
                <span class="value">{{ trackInfo.stayPoints }}个</span>
              </div>
            </div>
            <el-button type="primary" size="small" @click="clearTrack">清除轨迹</el-button>
          </div>
        </el-card>
      </el-col>

      <!-- 右侧地图区域 -->
      <el-col :span="18">
        <div class="map-container" ref="mapContainer"></div>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import AMapLoader from '@amap/amap-jsapi-loader';
import { getPoliceForceOverview, getTodayDutyMonitor, getMonthlyDutyStats } from '@/api/monitor/map';

export default {
  name: 'MonitorMap',
  data() {
    return {
      loading: false,
      map: null,
      markers: [],
      polyline: null, // 轨迹线
      selectedPolice: null, // 选中的警员
      // 警力概况数据
      policeForceData: {
        totalPolice: 0,
        regularPolice: 0,
        auxiliaryPolice: 0,
        onDutyTotal: 0,
        onDutyRegular: 0,
        onDutyAuxiliary: 0
      },
      // 当日勤务监管数据
      dutyMonitorData: {
        onlinePoints: {
          scheduled: 0,
          actual: 0
        },
        offlinePatrol: {
          scheduled: 0,
          actual: 0
        }
      },
      // 本月勤务统计数据
      monthlyStats: [],
      // 警员位置数据
      policeData: [
        {
          id: '1',
          name: '张三',
          position: [114.085947, 22.547],  // 深圳市中心
          type: '民警',
          status: '在岗',
          team: '一大队'
        },
        {
          id: '2',
          name: '李四',
          position: [114.114634, 22.550751],  // 福田区
          type: '民警',
          status: '在岗',
          team: '二大队'
        },
        {
          id: '3',
          name: '王五',
          position: [114.226478, 22.545431],  // 罗湖区
          type: '辅警',
          status: '在岗',
          team: '三大队'
        }
      ],
      // 轨迹数据
      trackData: {
        '1': [
          [114.085947, 22.547],
          [114.090947, 22.552],
          [114.095947, 22.550],
          [114.100947, 22.548],
          [114.105947, 22.545],
          [114.110947, 22.542],
          [114.115947, 22.540],
          [114.120947, 22.538],
          [114.125947, 22.535],
          [114.130947, 22.532]
        ],
        '2': [
          [114.114634, 22.550751],
          [114.119634, 22.548751],
          [114.124634, 22.546751],
          [114.129634, 22.544751],
          [114.134634, 22.542751],
          [114.139634, 22.540751],
          [114.144634, 22.538751],
          [114.149634, 22.536751],
          [114.154634, 22.534751],
          [114.159634, 22.532751]
        ],
        '3': [
          [114.226478, 22.545431],
          [114.221478, 22.543431],
          [114.216478, 22.541431],
          [114.211478, 22.539431],
          [114.206478, 22.537431],
          [114.201478, 22.535431],
          [114.196478, 22.533431],
          [114.191478, 22.531431],
          [114.186478, 22.529431],
          [114.181478, 22.527431]
        ]
      },
      // 轨迹信息
      trackInfo: {
        totalDistance: 0,
        patrolTime: 0,
        stayPoints: 0
      },
      // 定时器
      timer: null
    };
  },
  mounted() {
    this.initMap();
    this.fetchAllData();

    // 设置定时刷新
    this.timer = setInterval(() => {
      this.fetchAllData();
    }, 60000); // 每分钟刷新一次数据
  },
  beforeDestroy() {
    if (this.map) {
      this.map.destroy();
    }

    // 清除定时器
    if (this.timer) {
      clearInterval(this.timer);
    }
  },
  methods: {
    // 获取所有数据
    fetchAllData() {
      this.loading = true;

      // 获取警力概况数据
      this.fetchPoliceForceData();

      // 获取当日勤务监管数据
      this.fetchDutyMonitorData();

      // 获取本月勤务统计数据
      this.fetchMonthlyStatsData();
    },

    // 获取警力概况数据
    fetchPoliceForceData() {
      getPoliceForceOverview().then(res => {
        if (res.code === 200) {
          this.policeForceData = res.data;
        } else {
          this.$message.error('获取警力概况数据失败');
        }
        this.loading = false;
      }).catch(() => {
        this.loading = false;
      });
    },

    // 获取当日勤务监管数据
    fetchDutyMonitorData() {
      getTodayDutyMonitor().then(res => {
        if (res.code === 200) {
          this.dutyMonitorData = res.data;
        } else {
          this.$message.error('获取当日勤务监管数据失败');
        }
      });
    },

    // 获取本月勤务统计数据
    fetchMonthlyStatsData() {
      getMonthlyDutyStats().then(res => {
        if (res.code === 200) {
          this.monthlyStats = res.data.map(item => {
            return {
              type: item.type + '(次)',
              count: item.count
            };
          });
        } else {
          this.$message.error('获取本月勤务统计数据失败');
        }
      });
    },

    async initMap() {
      try {
        // 加载高德地图
        const AMap = await AMapLoader.load({
          key: '4b98d24146ee2f4b43cc046b7886cb71',
          version: '2.0',
          plugins: ['AMap.ToolBar', 'AMap.Scale', 'AMap.HawkEye', 'AMap.MapType', 'AMap.Geolocation']
        });

        // 创建地图实例
        this.map = new AMap.Map(this.$refs.mapContainer, {
          zoom: 12,
          center: [114.085947, 22.547],  // 深圳市中心坐标
          viewMode: '3D'
        });

        // 添加地图控件
        this.map.addControl(new AMap.ToolBar());
        this.map.addControl(new AMap.Scale());
        this.map.addControl(new AMap.HawkEye({isOpen: true}));
        this.map.addControl(new AMap.MapType());
        this.map.addControl(new AMap.Geolocation());

        // 添加警员标记
        this.addPoliceMarkers();
      } catch (e) {
        console.error('地图加载失败', e);
      }
    },
    addPoliceMarkers() {
      this.policeData.forEach(police => {
        const marker = new AMap.Marker({
          position: police.position,
          icon: new AMap.Icon({
            size: new AMap.Size(40, 50),
            image: require('@/assets/images/Police.png'),
            imageSize: new AMap.Size(40, 50)
          }),
          offset: new AMap.Pixel(-20, -50)
        });

        // 创建信息窗体
        const infoWindow = new AMap.InfoWindow({
          content: `
            <div class="info-window">
              <h4>${police.name}</h4>
              <p>类型：${police.type}</p>
              <p>状态：${police.status}</p>
              <p>所属队伍：${police.team}</p>
              <p><button onclick="window.showTrack('${police.id}')" style="background: #409EFF; color: white; border: none; padding: 5px 10px; border-radius: 3px; cursor: pointer;">查看轨迹</button></p>
            </div>
          `,
          offset: new AMap.Pixel(0, -30)
        });

        // 绑定点击事件
        marker.on('click', () => {
          infoWindow.open(this.map, marker.getPosition());
        });

        marker.setMap(this.map);
        this.markers.push(marker);
      });

      // 将轨迹显示方法挂载到全局
      window.showTrack = this.showTrack.bind(this);
    },

    // 显示轨迹
    showTrack(policeId) {
      // 清除之前的轨迹
      this.clearTrack();

      // 获取警员信息
      const police = this.policeData.find(p => p.id === policeId);
      if (!police) return;

      this.selectedPolice = police;

      // 获取轨迹数据
      const trackPoints = this.trackData[policeId];
      if (!trackPoints || trackPoints.length === 0) {
        this.$message.warning('暂无轨迹数据');
        return;
      }

      // 计算轨迹信息
      this.calculateTrackInfo(trackPoints);

      // 绘制轨迹线
      this.drawTrackLine(trackPoints);

      // 调整地图视野以包含整个轨迹
      this.map.setFitView();

      this.$message.success(`已显示${police.name}的轨迹信息`);
    },

    // 绘制轨迹线
    drawTrackLine(points) {
      if (!this.map) return;

      this.polyline = new AMap.Polyline({
        path: points,
        strokeColor: '#409EFF',
        strokeWeight: 4,
        strokeOpacity: 0.8,
        strokeStyle: 'solid'
      });

      this.polyline.setMap(this.map);

      // 添加起点和终点标记
      const startMarker = new AMap.Marker({
        position: points[0],
        icon: new AMap.Icon({
          size: new AMap.Size(20, 20),
          image: '',
          imageSize: new AMap.Size(20, 20)
        })
      });

      const endMarker = new AMap.Marker({
        position: points[points.length - 1],
        icon: new AMap.Icon({
          size: new AMap.Size(20, 20),
          image: '',
          imageSize: new AMap.Size(20, 20)
        })
      });

      startMarker.setMap(this.map);
      endMarker.setMap(this.map);

      // 添加方向箭头
      for (let i = 0; i < points.length - 1; i += 2) {
        const midPoint = [
          (points[i][0] + points[i + 1][0]) / 2,
          (points[i][1] + points[i + 1][1]) / 2
        ];

        const arrowMarker = new AMap.Marker({
          position: midPoint,
          icon: new AMap.Icon({
            size: new AMap.Size(16, 16),
            image: '',
            imageSize: new AMap.Size(16, 16)
          })
        });

        arrowMarker.setMap(this.map);
      }
    },

    // 计算轨迹信息
    calculateTrackInfo(points) {
      let totalDistance = 0;
      const stayPoints = Math.floor(Math.random() * 5) + 2; // 随机生成2-6个停留点

      // 计算总距离（简化计算）
      for (let i = 1; i < points.length; i++) {
        const lat1 = points[i - 1][1];
        const lon1 = points[i - 1][0];
        const lat2 = points[i][1];
        const lon2 = points[i][0];

        // 使用简化的距离计算公式
        const distance = Math.sqrt(
          Math.pow((lat2 - lat1) * 111000, 2) + 
          Math.pow((lon2 - lon1) * 111000 * Math.cos(lat1 * Math.PI / 180), 2)
        ) / 1000; // 转换为公里

        totalDistance += distance;
      }

      this.trackInfo = {
        totalDistance: totalDistance.toFixed(2),
        patrolTime: (totalDistance * 0.5 + Math.random() * 2).toFixed(1), // 根据距离估算时间
        stayPoints: stayPoints
      };
    },

    // 清除轨迹
    clearTrack() {
      if (this.polyline) {
        this.polyline.setMap(null);
        this.polyline = null;
      }

      // 清除地图上的所有标记（除了警员标记）
      this.map.clearMap();
      
      // 重新添加警员标记
      this.addPoliceMarkers();

      this.selectedPolice = null;
      this.trackInfo = {
        totalDistance: 0,
        patrolTime: 0,
        stayPoints: 0
      };
    }
  }
};
</script>

<style lang="scss" scoped>
.map-container {
  height: 800px;
  width: 100%;
  border-radius: 4px;
  overflow: hidden;
}

.box-card {
  margin-bottom: 20px;
}

.total-stats {
  .stat-item {
    margin-bottom: 20px;

    .title {
      font-size: 16px;
      font-weight: bold;
      margin-bottom: 10px;
    }

    .count {
      font-size: 24px;
      color: #409EFF;

      .sub-count {
        font-size: 14px;
        color: #666;
        margin-top: 5px;
      }
    }
  }
}

.duty-stats {
  margin-top: 20px;

  .title {
    font-size: 16px;
    font-weight: bold;
    margin-bottom: 15px;
  }

  .duty-items {
    .duty-item {
      margin-bottom: 10px;
      padding: 10px;
      background: #f5f7fa;
      border-radius: 4px;

      &:last-child {
        margin-bottom: 0;
      }
    }
  }
}

.month-stats {
  margin-top: 20px;

  .title {
    font-size: 16px;
    font-weight: bold;
    margin-bottom: 15px;
  }
}

.track-info {
  margin-top: 20px;
  padding: 15px;
  background: #f0f9ff;
  border-radius: 4px;
  border-left: 4px solid #409EFF;

  .title {
    font-size: 16px;
    font-weight: bold;
    margin-bottom: 15px;
    color: #409EFF;
  }

  .track-stats {
    margin-bottom: 15px;

    .track-item {
      display: flex;
      justify-content: space-between;
      margin-bottom: 8px;
      font-size: 14px;

      .value {
        font-weight: bold;
        color: #409EFF;
      }
    }
  }
}

:deep(.info-window) {
  padding: 10px;

  h4 {
    margin: 0 0 10px 0;
  }

  p {
    margin: 5px 0;
  }
}
</style>
